package com.company.dcm.common;

import cn.dev33.satoken.exception.NotLoginException;
import cn.dev33.satoken.exception.NotPermissionException;
import cn.dev33.satoken.exception.NotRoleException;
import com.company.dcm.exception.CustomizedException;
import com.company.dcm.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.catalina.connector.ClientAbortException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.sql.SQLIntegrityConstraintViolationException;

/**
 * 全局异常处理
 */
@ControllerAdvice(annotations = {RestController.class, Controller.class})
@ResponseBody
@Slf4j
public class GlobalExceptionHandler {

    /**
     * 违反了数据库的唯一约束条件
     */
    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public R<String> exceptionHandler(SQLIntegrityConstraintViolationException ex){
        log.error(ex.getMessage());

        if(ex.getMessage().contains("Duplicate entry")){
            String[] split = ex.getMessage().split(" ");
            String msg = split[2] + "已存在";
            return R.error(msg);
        }
        return R.error("未知错误");
    }

    /**
     * 定制的错误
     */
    @ExceptionHandler(CustomizedException.class)
    public R<String> exceptionHandler(CustomizedException ex){
        if(!StringUtils.isNullOrEmpty(ex.getMessage()))
        log.warn(ex.getMessage());
        return R.error(ex.getMessage());
    }

    @ExceptionHandler({NotLoginException.class, NotRoleException.class, NotPermissionException.class})
    public R<String> unauthorized(Exception e) {
        if(!StringUtils.isNullOrEmpty(e.getMessage()))
            log.warn(e.getMessage());
        return R.error("未登录，或权限不足！");
    }

    @ExceptionHandler(ClientAbortException.class)
    public R<String> exceptionHandler(ClientAbortException e){
            log.warn("Connection reset by peer!");
        return R.error("连接断开！");
    }

}
